<template>
    <el-dialog   :title="state.dialog.title"
    v-model="state.dialog.isShowDialog"
    :before-close="close" width="450px">
        <el-tree ref="treeRef" style="max-width: 450px;min-height: 400px;" 
        :data="state.menuData" 
        show-checkbox 
        default-expand-all
        highlight-current 
        node-key="id" 
        :default-checked-keys="state.saveMenuIds"
        :props="defaultProps" />

        <div class="buttons">
            <el-button  @click="close">取消</el-button>
            <el-button type="primary" @click="onSubmit">保存</el-button>
        </div>
    </el-dialog>
</template>

<script setup name="selectMenu">

import { onMounted, ref,reactive } from 'vue'
import { Menu } from '/@/api'

const emits = defineEmits(['handleSubmit'])

const treeRef = ref()
const defaultProps = {
    children: 'children',
    label:function(data,node){
        return data.meta.title
    },
}
const state = reactive({
    queryForm: {
        conditions: []
    },
    //菜单树形列表
    menuData: [],
    assignSubject:'',
    saveMenuIds:[],
    dialog:{
        isShowDialog:false,
        title:'分配菜单'
    }
})

const openAssignDialog=(assignId,initMenuIdsArr)=>{
    state.dialog.isShowDialog = true
    state.assignSubject= assignId
    console.log(initMenuIdsArr);
    
    state.saveMenuIds = initMenuIdsArr
}

const close=()=>{
    //先清除选中，在进行弹出框关闭操作，不然before-close操作会对清除不起作用
    resetChecked()
    state.dialog.isShowDialog = false
}

const resetChecked = () => {
  treeRef.value?.setCheckedKeys([], false)
}

const onSubmit = () => {
  let keys=treeRef.value?.getCheckedKeys(false)
  emits('handleSubmit',keys,state.assignSubject)
  close()
}

const initMenuList = async () => {
    await Menu.postMenusByTree(state.queryForm).then(res => state.menuData = res.data)
}
onMounted(() => {
    initMenuList()
})
defineExpose({
    openAssignDialog
})
</script>

<style lang="scss" scoped>
.buttons{
    display: flex;
    justify-content: right;
    align-items: center;
}
</style>